package com.peter.image.manage.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.peter.image.manage.fs.FsManager;
import com.peter.image.manage.fs.FsManager.Organization;

@RestController
@RequestMapping("image")
public class ImageController {
    @Autowired
    private Environment env;

    @Autowired
    private FsManager fs;

    private static Logger logger = LogManager.getLogger(ImageController.class);

    @RequestMapping("/")
    public String list(@RequestParam(name = "path", required = false, defaultValue = "/") String path,
            @RequestParam(name = "page", required = false, defaultValue = "0") int page,
            Model model)
    {
        String rootpath = this.env.getProperty("image.store.path");
        logger.info(String.format(">>> rootpath: %s", rootpath));

        List<File> folders = fs.listByStartId(Organization.MEITURI, 0, 20);
        List<String> names = new ArrayList<String>();

        for (File folder : folders) {
            logger.info(String.format(">>> path: %s", folder.getAbsolutePath()));
            names.add(folder.getName());
        }

        model.addAttribute("root", rootpath);
        model.addAttribute("names", names);
        return "image/list";
    }

    @RequestMapping("/list")
    public HashMap<String, Object>  list(@RequestParam(name = "id", required = false, defaultValue = "0") int id,
            Model model)
    {
        HashMap<String, Object> result = new HashMap<String, Object>();
        List<Integer> ids = this.listById(Organization.MEITURI, id);
        result.put("status", ids.size() == 0 ? 202 : 200);
        result.put("msg", ids.size() == 0 ? "请求列表失败" : "请求列表成功");
        result.put("data", ids);
        return result;
    }


    @RequestMapping("/start-view")
    public HashMap<String, Object>  start() {
        int startId = 24500;
        String path = fs.getPathByName(Organization.MEITURI, startId);
        List<String> images = fs.getImagesInFolder(path);
        List<Integer> ids = this.listById(Organization.MEITURI, startId);

        HashMap<String, Object> data = new HashMap<String, Object>();
        data.put("id", startId);
        data.put("ids", ids);
        data.put("images", images);

        HashMap<String, Object> result = new HashMap<String, Object>();
        result.put("status", images == null ? 202 : 200);
        result.put("msg", images == null ? "此套图不存在" : "请求成功");
        result.put("data", data);
        return result;
    }

    @RequestMapping("/view")
    public HashMap<String, Object> view(@RequestParam(name = "id", required = false, defaultValue = "24000") int id,
            Model model) {
        String path = fs.getPathByName(Organization.MEITURI, id);
        List<String> images = fs.getImagesInFolder(path);

        model.addAttribute("error", "");
        model.addAttribute("images", images);
        HashMap<String, Object> result = new HashMap<String, Object>();
        result.put("status", images == null ? 202 : 200);
        result.put("msg", images == null ? "此套图不存在" : "请求成功");
        result.put("data", images);
        return result;
    }

    @RequestMapping("/delete")
    public HashMap<String, Object> delete(@RequestParam(name = "id", required = false, defaultValue = "24000") int id,
            Model model) {
        boolean delStatue = fs.deleteFolder(Organization.MEITURI, id);
        HashMap<String, Object> result = new HashMap<String, Object>();
        result.put("status", delStatue ? 200 : 202);
        result.put("msg", delStatue ? "删除成功" : "删除失败");
        return result;
    }

    @RequestMapping("/favorite")
    public HashMap<String, Object> favorite(@RequestParam(name = "id", required = false, defaultValue = "24000") int id,
            Model model) {
        boolean favoriteStatue = false;

        try {
            favoriteStatue = fs.favorite(Organization.MEITURI, id);
        } catch (IOException e) {
            logger.catching(e);
        }

        HashMap<String, Object> result = new HashMap<String, Object>();
        result.put("status", favoriteStatue ? 200 : 202);
        result.put("msg", favoriteStatue ? "收藏成功" : "收藏失败");

        return result;
    }

    private List<Integer>  listById(Organization org, int id) {
        List<Integer> ids = new ArrayList<Integer>();
        int tempId = id;

        while(true) {
            List<File> files = fs.listByOneId(org, tempId);
            List<Integer> list = new ArrayList<Integer>();

            for(File file: files) {
                list.add(Integer.valueOf(file.getName()));
            }

            if(id <= tempId) {
                ids.addAll(list);
            }
            else {
                ids.addAll(0, list);
            }

            int indexOfId = ids.indexOf(id);

            if((indexOfId < 0 || indexOfId > ids.size() - 3) && ids.get(ids.size() - 1) <= id) {
                tempId = (tempId < id ? id : tempId) + 100;
            }
            else if(indexOfId < 2 && ids.get(0) >= id) {
                tempId = (tempId > id ? id : tempId) - 100;
            }
            else {
                break;
            }

            if(tempId < 0) {
                break;
            }
        }

        return ids;
    }

    @Override
    public String toString() {
        return super.toString();
    }
}
